package com.jiangnan.utils;

import com.jiangnan.constants.ColorSelect;
import com.jiangnan.constants.Constants;
import com.jiangnan.constants.TopButton;
import com.jiangnan.enums.Protocol;
import com.jiangnan.filter.JsonFileFilter;
import com.jiangnan.filter.PcapFileFilter;
import com.jiangnan.model.TableData;
import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;
import org.apache.tika.Tika;

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import java.awt.*;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

/**
 *
 *  swing组件工具类
 *
 * @author chenliang
 * @email wschenliang@aliyun.com
 */
public class SwingUtil {
    private final static String PCAP = "application/vnd.tcpdump.pcap";
    protected static final Logger logger = LoggerFactory.getLogger(SwingUtil.class);

    public static JTable getJTable(String[] columnName) {
        DefaultTableModel model = new DefaultTableModel(null, columnName);
        JTable jTable = new JTable(model){
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;//不允许被编辑
            }

            @Override
            public boolean getScrollableTracksViewportWidth() {
                return getPreferredSize().width < getParent().getWidth();
            }
        };
        jTable.setRowHeight(25);//每条数据的单行高度
        jTable.setFont(Constants.GENERAL_FONT);
        jTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        jTable.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);//设置表格，每次点击选择一个连续得范围
        setTableColor(jTable);//设置颜色
        notShow(jTable, 7,8);
        return jTable;
    }

    public static JComboBox<String> getComboBox(String[] selectItem) {
        JComboBox<String> box = new JComboBox<>(selectItem);
        box.setPreferredSize(new Dimension(150,25));
        return box;
    }

    public static JFileChooser getFileChooser(int fileChooserStyle) {
        JFileChooser fileChooser = new JFileChooser(".");
        fileChooser.addChoosableFileFilter(new PcapFileFilter());
        fileChooser.addChoosableFileFilter(new JsonFileFilter());
        fileChooser.setDialogType(fileChooserStyle);
        return fileChooser;
    }

    public static JMenuItem getMenuItem(String text, ActionListener l) {
        JMenuItem item = new JMenuItem(text);
        item.setFont(Constants.GENERAL_FONT);
        item.addActionListener(l);
        return item;
    }

    public static JCheckBox getCheckBox(String text) {
        JCheckBox jCheckBox = new JCheckBox(text);
        jCheckBox.setFont(Constants.GENERAL_FONT);
        return jCheckBox;
    }

    public static JButton getTopButton(TopButton topButton) {
        JButton jButton = new JButton();
        jButton.setBackground(Color.WHITE);
        jButton.setToolTipText(topButton.getTipText());
        jButton.setBorderPainted(false);//不打印边框
//        jButton.setBorder(null);//除去边框
        jButton.setFocusPainted(false);//除去焦点边框
//        jButton.setContentAreaFilled(false);//除去默认填充
        jButton.setMargin(new Insets(0,0,0,0));
        Icon icon = topButton.getIcon();
        if (icon == null) {
            jButton.setText(topButton.getText());
        } else {
            jButton.setIcon(icon);
        }
        return jButton;
    }

    public static JTextArea getBottomArea(String text, boolean isEditable) {
        JTextArea jTextArea = new JTextArea(text) {
            @Override
            public boolean isEditable() {
                return isEditable;
            }
        };
        jTextArea.setFont(Constants.GENERAL_FONT);
        jTextArea.setCursor(new Cursor(Cursor.TEXT_CURSOR));//设置鼠标变为文本鼠标
        jTextArea.setBackground(Color.LIGHT_GRAY);
        return jTextArea;
    }

    //设置组件是否启用
    public static void EnableComponent(boolean isEnable, Component... components) {
        if (components == null) {
            return;
        }
        for (Component component : components) {
            component.setEnabled(isEnable);
        }
    }

    /**
     * 设置表格的某一行的背景色
     * @param table
     */
    public static void setOneRowBackgroundColor(JTable table, int rowIndex,
                                                Color color) {
        try {
            DefaultTableCellRenderer tcr = new DefaultTableCellRenderer() {

                public Component getTableCellRendererComponent(JTable table,
                                                               Object value, boolean isSelected, boolean hasFocus,
                                                               int row, int column) {
                    if (row == rowIndex) {
                        setBackground(color);
                        setForeground(Color.WHITE);
                    }
                    else if(row > rowIndex){
                        setBackground(Color.WHITE);
                        setForeground(Color.BLACK);
                    }else{
                        setBackground(Color.WHITE);
                        setForeground(Color.BLACK);
                    }

                    return super.getTableCellRendererComponent(table, value,
                            isSelected, hasFocus, row, column);
                }
            };
            int columnCount = table.getColumnCount();
            for (int i = 0; i < columnCount; i++) {
                table.getColumn(table.getColumnName(i)).setCellRenderer(tcr);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    //表格中那些数据不展示
    public static void notShow(JTable jTable, int startColumn, int endColumn) {
        TableColumnModel columnModel = jTable.getColumnModel();
        int columnCount = columnModel.getColumnCount();
        if (startColumn > columnCount) {
            LogUtils.log("不展示的数据超了");
            return;
        }
        if (endColumn >= columnCount) {
            endColumn = columnCount - 1;
        }
        for (int i = startColumn; i <= endColumn; i ++) {
            TableColumn column = columnModel.getColumn(i);
            column.setMaxWidth(0);
            column.setMinWidth(0);
            column.setPreferredWidth(0);
        }
    }


    public static void setTableColor(JTable jTable) {
        try {
            DefaultTableCellRenderer tcr = new DefaultTableCellRenderer() {

                public Component getTableCellRendererComponent(JTable table,
                                                               Object value, boolean isSelected, boolean hasFocus,
                                                               int row, int column) {
                    //Color[] colors = {Color.WHITE, Color.LIGHT_GRAY};
                    DefaultTableModel model = (DefaultTableModel) jTable.getModel();
                    String protocol = (String) model.getValueAt(row, 4);
                    if (Protocol.UDP.getName().equals(protocol)) {
                        setBackground(ColorSelect.BLUE_BG);
                    } else if (Protocol.ARP.getName().equals(protocol)) {
                        setBackground(ColorSelect.YELLOW_BG);
                    }else if (Protocol.OTHER.getName().equals(protocol)) {
                        setBackground(Color.RED);
                    } else {
                        setBackground(ColorSelect.NORMAL_BG);
                    }
                    setForeground(Color.BLACK);

                    return super.getTableCellRendererComponent(table, value,
                            isSelected, hasFocus, row, column);
                }
            };
            int columnCount = jTable.getColumnCount();
            for (int i = 0; i < columnCount; i++) {
                jTable.getColumn(jTable.getColumnName(i)).setCellRenderer(tcr);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static boolean isPcapFile(File file) {

        if (file == null) {
            return false;
        }

        try {

            String contentType;
            contentType = new Tika().detect(file);
            if (PCAP.equalsIgnoreCase(contentType)) {
                return true;
            }else{
                return false;
            }
        } catch (IOException e) {
            logger.debug(e.getMessage());
        }

        return false;
    }

    public static void setBorderLayoutPane(Container container, Component comp, Object constraints){

        if (container == null) {
            throw new IllegalArgumentException("BorderLayoutPane cannot be null!!");
        }

        BorderLayout layout = (BorderLayout) container.getLayout();
        Component oldComp = layout.getLayoutComponent(constraints);

        if(oldComp==null) {
            if(comp!=null) {
                container.add(comp,constraints);
            }
            container.repaint();
            container.revalidate();
        }else {
            if(comp!=oldComp) {
                container.remove(oldComp);
                if(comp!=null) {
                    container.add(comp,constraints);
                }
                container.repaint();
                container.revalidate();
            }
        }
    }
}
